<template>
  <ElDialog
    v-model="dialogVisible"
    :title="dialogType === 'add' ? '添加标签' : '编辑标签'"
    width="500px"
    align-center
    :close-on-click-modal="false"
  >
    <ElForm ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <ElFormItem label="标签名称" prop="tagName">
        <ElInput
          v-model="formData.tagName"
          placeholder="请输入标签名称"
          maxlength="20"
          show-word-limit
        />
      </ElFormItem>
    </ElForm>

    <template #footer>
      <div class="dialog-footer">
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" :loading="submitLoading" @click="handleSubmit" v-ripple>
          确定
        </ElButton>
      </div>
    </template>
  </ElDialog>
</template>

<script setup lang="ts">
  import type { FormInstance, FormRules } from 'element-plus'
  import { ElMessage } from 'element-plus'
  import {
    apiTagSaveDataUsingPost,
    apiTagUpdateDataUsingPost,
    type ApiTagVo
  } from '@/api'

  interface Props {
    visible: boolean
    type: 'add' | 'edit'
    tagData?: ApiTagVo
  }

  interface Emits {
    (e: 'update:visible', value: boolean): void
    (e: 'submit'): void
  }

  const props = defineProps<Props>()
  const emit = defineEmits<Emits>()

  // 对话框显示控制
  const dialogVisible = computed({
    get: () => props.visible,
    set: (value) => emit('update:visible', value)
  })

  const dialogType = computed(() => props.type)

  // 表单实例
  const formRef = ref<FormInstance>()
  const submitLoading = ref(false)

  // 表单数据
  const formData = reactive({
    id: undefined as number | undefined,
    tagName: ''
  })

  // 表单验证规则
  const rules: FormRules = {
    tagName: [
      { required: true, message: '请输入标签名称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ]
  }

  // 初始化表单数据
  const initFormData = () => {
    const isEdit = props.type === 'edit' && props.tagData
    const row = props.tagData

    if (isEdit && row) {
      Object.assign(formData, {
        id: row.id,
        tagName: row.tagName || ''
      })
    } else {
      Object.assign(formData, {
        id: undefined,
        tagName: ''
      })
    }
  }

  // 统一监听对话框状态变化
  watch(
    () => [props.visible, props.type, props.tagData],
    ([visible]) => {
      if (visible) {
        initFormData()
        nextTick(() => {
          formRef.value?.clearValidate()
        })
      }
    },
    { immediate: true }
  )

  // 提交表单
  const handleSubmit = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()
      submitLoading.value = true

      let res
      if (dialogType.value === 'add') {
        // 添加标签
        res = await apiTagSaveDataUsingPost({
          body: {
            tagName: formData.tagName
          }
        })
      } else {
        // 编辑标签 - 注意：根据API定义，更新接口只需要tagName，不需要id
        res = await apiTagUpdateDataUsingPost({
          body: {
            id: formData.id,
            tagName: formData.tagName
          }
        })
      }
      console.log('res:', res)

      if (res) {
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '编辑成功')
        dialogVisible.value = false
        emit('submit')
      } else {
        ElMessage.error('操作失败')
      }
    } catch (error: any) {
      if (error !== false) {
        // false 是表单验证失败返回的
        console.error('提交标签数据失败:', error)
        ElMessage.error('操作失败')
      }
    } finally {
      submitLoading.value = false
    }
  }
</script>

<style lang="scss" scoped>
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
  }
</style>
